<?php

namespace app\modules\Order\controllers;

use Yii;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderRoomCustomer;
use app\modules\Order\models\OrderRoomCustomerSearch;
use app\modules\Order\models\OrderRoom;
use app\modules\Order\models\OrderCustomer;
use app\modules\Order\models\OrderPrice;
use app\modules\Order\models\OrderPriceType;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

/**
 * RoomCustomerController implements the CRUD actions for OrderRoomCustomer model.
 */
class RoomCustomerController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }


	// 客户添加和取消
    public function actionSave(){ //{{{
        $model = new OrderRoomCustomer();

        $data = Yii::$app->request->get();

        $orderRoomModel = OrderRoom::findOne($data['order_room_id']);
		$customer = OrderCustomer::findOne($data['customer_id']);

        //$db = Yii::$app->db;
        //$transaction = $db->beginTransaction();

        //$transaction->commit();

        if($data['checked'] == 'true'){
            $ret = OrderRoomCustomer::find()->where(['order_id'=>$orderRoomModel->order_id, 'customer_id'=>$data['customer_id'], 'order_room_id'=>$data['order_room_id']])->one();

            if(empty($ret)){
                $model->order_id = $orderRoomModel->order_id; 
                $model->customer_id = $data['customer_id'];
                $model->order_room_id = $data['order_room_id'];
                $model->save();
				$customer->status =1;
				$ret = $customer->save();
				if($ret){
                    //必选附加费
                    $orderPriceType = OrderPriceType::find()->where(['product_id'=>$orderRoomModel->order->product_id,'type'=>2])->all();
                    if($orderPriceType){
                        foreach($orderPriceType as $opt){
                            $orderPrice = OrderPrice::find()->where(['type'=>$opt->id,'order_id'=>$orderRoomModel->order_id])->one();
                            if($orderPrice){
                                $orderPrice->num = $orderPrice->num+1;
                                $customers = json_decode($orderPrice->customers);
                                array_push($customers,$data['customer_id']);
                                $orderPrice->customers = $customers;
                                $orderPrice->save();
                            }else{
                                $orderPrice = new OrderPrice();
                                $orderPrice->desc = $opt->desc;
                                $orderPrice->price = $opt->price;
                                $orderPrice->num = 1;
                                $orderPrice->order_id = $order->id;
                                $orderPrice->type = $opt->id;
                                $customers = [$data['customer_id']];
                                $orderPrice->customers = $customers;
                                $orderPrice->save();
                            }
                        }
                    }
					echo "success";	
				}
            }else{
                echo "该记录已经存在";
            }
        }else{
            $ret = OrderRoomCustomer::find()->where( ['order_id'=>$orderRoomModel->order_id, 'customer_id'=>$data['customer_id'], 'order_room_id'=>$data['order_room_id']] )->one();

            if($ret){
				// 取消客户与船舱的关联关系
				/**
				 * 1. 是否选择了附加费
				 * 2. 用户所属订单是否已分团 
				 * 
				 */
				$orders = OrderPrice::find()->where(['order_id'=>$orderRoomModel->order_id])->all();

				foreach($orders as $order_price){
					if($order_price->customers && $order_price->typeObj->type !=2){
						$all = json_decode($order_price->customers);
						if(in_array($data['customer_id'], $all)){
							echo 'order-price-exit';
							return;
						}
					}
				}

				$model = Order::findOne($orderRoomModel->order_id);
				if($model->assign_id){
					echo 'order-assign-exit';
					return;
				}


                if($ret->delete()){
					$customer->status =2;
					$customer->save();
                    if($customer->save()){
                        //必选附加费
                        $orders = OrderPrice::find()->where(['order_id'=>$orderRoomModel->order_id])->all();
                        foreach($orders as $order_price){
                            if($order_price->typeObj->type ==2){
                                $all = json_decode($order_price->customers);
                                if($all){
                                    foreach($all as $k=>$cid){
                                        if($cid == $data['customer_id']){
                                            unset($all[$k]);
                                        }
                                    }
                                }
                                if(empty($all)){
                                    $order_price->delete();
                                }else{
                                    $order_price->num = $order_price->num-1;
                                    $order_price->customers = array_values($all);
                                    $order_price->save();
                                }
                            }
                        }
                      
                    }
				}
            }
            echo "delete";
        }
    }//}}}

    /**
     * Lists all OrderRoomCustomer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new OrderRoomCustomerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single OrderRoomCustomer model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new OrderRoomCustomer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new OrderRoomCustomer();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing OrderRoomCustomer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing OrderRoomCustomer model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the OrderRoomCustomer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return OrderRoomCustomer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = OrderRoomCustomer::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
